package com.github.llyb120.yaomq.server;


import com.alibaba.fastjson.JSON;
import lombok.Synchronized;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.github.llyb120.yaomq.server.MQService.*;
import static com.github.llyb120.yaomq.server.WebSocketConfig.authToken;

@ServerEndpoint(value = "/_connect")
@Component
public class WebSocketServer {

    private String getParameter(Map<String, List<String>> map, String key){
        List<String> list = map.get(key);
        if (list == null) {
            return  "";
        }
        if(list.isEmpty()){
            return "";
        }
        return list.get(0);
    }

    @OnOpen
    public void onOpen(Session session) throws IOException {
        Map<String, List<String>> map = session.getRequestParameterMap();
        String token = getParameter(map, "token");
        String name = getParameter(map, "name");
        if(token.isEmpty() || name.isEmpty() || !token.equals(authToken)){
            session.close();
            return;
        }
        saveSession(name, session);
//        System.out.println("opened");
//        throw new RuntimeException();
    }

    @OnClose
    public void onClose(Session session){
        cleanSession(session);
    }

    @OnMessage
    public void onMessage(Session session, String message){
        handleServerMessage(session, message);
        System.out.println("server received message");
        System.out.println(message);
    }


    @OnError
    public void onError(Session session, Throwable throwable){
        System.out.println("error");
        throwable.printStackTrace();
    }




}
